package test.chat.server;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

import com.n1global.asts.EndpointConfig;
import com.n1global.asts.MainLoop;
import com.n1global.asts.message.websocket.WebSocketMessage;
import com.n1global.asts.protocol.websocket.WebSocketProtocol;

@WebListener
public class ChatListener implements ServletContextListener {
    private Thread serverThread;

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        final MainLoop mainLoop = new MainLoop();

        mainLoop.addServer(new EndpointConfig.Builder<WebSocketMessage>().setHandlerClass(ChatWebSocketHandler.class)
                                                                         .setProtocolClass(WebSocketProtocol.class)
                                                                         .setLocalPort(8765)
                                                                         .build());

        serverThread = new Thread() {
            @Override
            public void run() {
                mainLoop.loop();
            }
        };

        serverThread.start();
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        serverThread.interrupt();

        try {
            serverThread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
